<template>
  <VPage class="app-container">
    <div class="relative" style="height: 100%">
      <CategoryWrap
        type="spu"
        @toggle="toggle"
        @nodeClick="handleNodeClick"
      ></CategoryWrap>
      <div
        class="rightWrap"
        :style="{ 'margin-left': isShowLeft ? containerWidth + 'px' : '0px' }"
      >
        <VTable ref="tableRef" v-bind="tableOptins" class="is--line" @keyup="handleKeyUp">
          <template #form="{ form }">
            <div class="w-full">
              <el-tabs v-model="activeName" @tab-change="handleChange">
                <el-tab-pane
                  :label="item.label"
                  :name="item.name"
                  v-for="(item, index) in tabFilterList"
                  :key="index"
                ></el-tab-pane>
              </el-tabs>
            </div>
            <template v-if="activeName == 1">
              <el-select
                class="!w-[150px]"
                v-model="form.sales_status"
                placeholder="产品分类"
                multiple
              >
                <el-option
                  v-for="item in options['goods.GoodsSku']?.[0].productTypeText"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </template>
            <VGroup>
              <el-select class="selectClass !w-[120px]" v-model="form.skuRange.type">
                <el-option
                  v-for="item in skuOptionss"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
              <multi-input
                v-model="form.skuRange.value"
                placeholder="批量搜索,一行一个"
                class="w-50"
              ></multi-input>
            </VGroup>
            <multi-input
              v-model="form.spu"
              placeholder="SPU,批量搜索,一行一个"
              class="w-50"
            ></multi-input>
            <VGroup>
              <el-select class="selectClass !w-[120px]" v-model="form.languageRange.type">
                <el-option
                  v-for="item in languageOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
              <el-input
                style="height: 32px"
                v-model="form.languageRange.value"
                placeholder="请输入"
                clearable
                class="!w-[160px]"
              />
            </VGroup>
            <select-warehouse
              v-model="form.warehouse_id"
              placeholder="仓库"
              style="max-width: 150px"
            ></select-warehouse>
            <template v-if="activeName == 0">
              <VGroup>
                <el-select
                  class="selectClass !w-[130px]"
                  v-model="form.salesStatusRange.type"
                >
                  <el-option
                    v-for="item in salesStatusOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
                <el-select
                  class="!w-[150px]"
                  v-model="form.salesStatusRange.value"
                  placeholder="销售状态"
                  clearable
                >
                  <el-option
                    v-for="item in options['goods.GoodsSku']?.[0].salesStatusText"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </VGroup>
            </template>

            <VGroup>
              <el-select
                class="selectClass w-[130px]"
                v-model="form.supplyStatusRange.type"
              >
                <el-option
                  v-for="item in supplyStatusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <el-select
                class="!w-[150px]"
                v-model="form.supplyStatusRange.value"
                placeholder="货源状态"
                clearable
              >
                <el-option
                  v-for="item in options['goods.GoodsSku']?.[0].supplyStatusText"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </VGroup>
            <VGroup>
              <el-select
                class="selectClass !w-[180px]"
                v-model="form.cleanProductStatusRange.type"
              >
                <el-option
                  v-for="item in cleanProductStatusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <el-select
                class="!w-[160px]"
                v-model="form.cleanProductStatusRange.value"
                placeholder="智能清洁产品状态"
                filterable
                clearable
              >
                <el-option
                  v-for="item in options['goods.GoodsSku']?.[0].cleanProductStatusText"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </VGroup>
            <VGroup>
              <el-select
                class="selectClass !w-[130px]"
                v-model="form.productStatusRange.type"
              >
                <el-option
                  v-for="item in productStatusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <el-select
                class="!w-[150px]"
                v-model="form.productStatusRange.value"
                placeholder="产品状态"
                filterable
                clearable
              >
                <el-option
                  v-for="item in options['goods.GoodsSpu']?.[0].spuStatusText"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </VGroup>
            <el-select
              class="!w-[150px]"
              v-model="form.is_combination"
              placeholder="是否组合SKU"
              clearable
            >
              <el-option
                v-for="item in options['goods.GoodsSku']?.[0].mainAttributeText"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
            <VGroup>
              <el-select
                class="selectClass !containerw-[120px]"
                v-model="form.timeRange.type"
              >
                <el-option
                  v-for="item in timeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
              <el-date-picker
                v-model="form.timeRange.value"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="max-width: 300px"
                :default-time="defaultTime()"
              />
            </VGroup>
            <VGroup>
              <el-select class="selectClass !w-[120px]" v-model="form.personRange.type">
                <el-option
                  v-for="item in personOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
              <select-personnel
                class="!w-[160px]"
                v-model="form.personRange.value"
                :multiple="true"
                placeholder="请选择"
              ></select-personnel>
            </VGroup>
            <el-select
              class="!w-[120px]"
              v-model="form.product_attribute"
              collapse-tags
              placeholder="类型"
              clearable
            >
              <el-option
                v-for="item in options['goods.GoodsSpu']?.[0].productAttributeText"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <template v-if="activeName == 0">
              <el-select
                class="!w-[150px]"
                v-model="form.sample_testing"
                placeholder="样品检测"
                clearable
              >
                <el-option
                  v-for="item in options['goods.GoodsSku']?.[0].sampleTestingText"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
              <el-select
                class="!w-[150px]"
                v-model="form.combined_sources"
                placeholder="组合类型"
                clearable
              >
                <el-option
                  v-for="item in options['goods.GoodsSpu']?.[0].combinedSourcesText"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
              <el-select
                v-model="form.is_dangerous"
                placeholder="是否危险品"
                class="!w-[160px]"
                clearable
              >
                <el-option
                  v-for="item in whetherOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
              <el-select
                v-model="form.spu_is_refund_tax"
                placeholder="是否备料"
                class="!w-[160px]"
                clearable
              >
                <el-option
                  v-for="item in whetherOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </template>
            <template v-if="activeName == 1">
              <el-select
                class="!w-[150px]"
                v-model="form.brand_type"
                clearable
                placeholder="品牌类型"
              >
                <el-option
                  v-for="item in options['goods.GoodsSpu']?.[0].brandTypeText"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <el-select
                class="!w-[150px]"
                v-model="form.goods_tag"
                clearable
                placeholder="季节标签"
                multiple
              >
                <el-option
                  v-for="item in options['goods.GoodsSpu']?.[0].goodsTagText"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <select-supplie
                class="!w-[160px]"
                v-model="form.supplier_id"
                placeholder="供应商"
              ></select-supplie>
              <VGroup class="no-border">
                <el-select
                  v-model="form.purchaseRange.type"
                  clearable
                  placeholder="请选择"
                  style="width: 90px"
                >
                  <el-option
                    v-for="item in purchaseList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
                <el-input-number
                  v-model="form.purchaseRange.start"
                  :controls="false"
                  placeholder="输入"
                  style="width: 80px"
                />
                <div class="v-group-item no-border-item">
                  <svg-icon icon-class="qujian" />
                </div>
                <el-input-number
                  v-model="form.purchaseRange.end"
                  :controls="false"
                  placeholder="输入"
                  style="width: 80px"
                />
                <div class="v-group-item">CNY</div>
              </VGroup>
              <VGroup class="no-border">
                <el-select
                  v-model="form.weightRange.type"
                  clearable
                  placeholder="请选择"
                  style="width: 90px"
                >
                  <el-option
                    v-for="item in weightList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
                <el-input-number
                  v-model="form.weightRange.start"
                  :controls="false"
                  placeholder="输入"
                  style="width: 90px"
                />
                <div class="v-group-item no-border-item">
                  <svg-icon icon-class="qujian" />
                </div>
                <el-input-number
                  v-model="form.weightRange.end"
                  :controls="false"
                  placeholder="输入"
                  style="width: 90px"
                />
                <div class="v-group-item">G</div>
              </VGroup>
            </template>
            <el-select
              class="!w-[160px]"
              v-model="form.recommended_level"
              collapse-tags
              placeholder="SPU等级"
              clearable
            >
              <el-option
                v-for="item in options['goods.GoodsSpu']?.[0].recommendLevelText"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-select
              class="!w-[160px]"
              v-model="form.product_level"
              placeholder="产品等级"
              filterable
              clearable
            >
              <el-option
                v-for="item in options['goods.GoodsSku']?.[0].productLevelText"
                :key="item.value"
                :value="item.value"
                :label="item.label"
              ></el-option>
            </el-select>
          </template>
          <template #purchasingInformation="{ row, level }">
            <div class="text-[#333333]" v-if="level == 0">
              <div>{{ row.warehouse_name || "--" }}</div>
              <div class="text-xs pb-1">
                采购未税报价:¥
                <dataAuthority
                  auth="unit_price"
                  :value="row.supplier_quotation"
                ></dataAuthority>
              </div>
              <div class="text-xs pb-1">
                采购未税价:¥
                <dataAuthority
                  auth="purchase_untaxed_price"
                  :value="row.purchase_untaxed_price"
                ></dataAuthority>
              </div>
              <div class="text-xs pb-1">
                采购含税价:¥
                <dataAuthority
                  auth="unit_price_tax"
                  :value="row.unit_price_tax"
                ></dataAuthority>
              </div>
            </div>
            <div class="text-[#333333]" v-else>
              <div class="flex">
                样品检测结果：
                <div v-if="row.sample_testing == 0">未检测</div>
                <div v-else-if="row.sample_testing == 1" class="flex items-center">
                  <svg-icon
                    icon-class="state_finish_cover1"
                    class="text-green-400"
                  />样品检测通过
                </div>

                <div v-else-if="row.sample_testing == 2" class="flex items-center">
                  <svg-icon icon-class="hint_cover1" class="text-red-400" />
                  样品检测异常
                </div>
              </div>
              <div class="flex justify-between">
                <div>
                  采购未税报价：¥
                  <span>
                    <dataAuthority
                      auth="unit_price"
                      :value="row.supplier_quotation"
                    ></dataAuthority>
                  </span>
                </div>
                <el-button type="primary" link @click="handlePurchaseRecord(row)"
                  >采购记录</el-button
                >
              </div>
              <div class="">
                采购未税价：¥
                <span>
                  <dataAuthority
                    auth="purchase_untaxed_price"
                    :value="row.purchase_untaxed_price"
                  ></dataAuthority>
                </span>
              </div>
              <div class="">
                采购含税价：¥
                <span>
                  <dataAuthority
                    auth="unit_price_tax"
                    :value="row.unit_price_tax"
                  ></dataAuthority>
                </span>
              </div>
              <div class="flex justify-between">
                <div class="flex items-center">
                  本地仓加权采购价
                  <el-tooltip class="item" effect="dark" placement="top">
                    <template #content>
                      说明<br />1、初始数据基于默认供应商报价，退税:取采购未税价；不退税：取采购未税报价
                      ；<br />
                      2、后续数据基于本地仓库加权成本（国内仓），取最大成本（排除样品仓）；<br />
                      3、在未获取到仓库加权成本前，修改默认供应商报价，将同步修改此加权成本；<br />
                      4、仓库加权成本，每天凌晨同步一次；<br />
                      5、组合SKU基于上述逻辑，按子SKU*组成量，进行计算；<br />
                      6、此成本用于运营在销售定价时进行参考，也可点击‘头程记录’查看该SKU的头程/库存数据；<br />
                    </template>
                    <svg-icon icon-class="QuestionFilled"></svg-icon> </el-tooltip
                  >:<dataAuthority
                    auth="purchase_weighted_cost"
                    :value="row.average_purchase_price"
                  ></dataAuthority>
                </div>
                <el-button type="primary" link @click="handleTcRecord(row)"
                  >头程记录</el-button
                >
              </div>
              <!-- <div class="">仓库加权成本（CNY）：¥{{ row.average_purchase_price }}</div>
              <div class="text-xs text-gray-500">最近¥0.00 /最低¥ 0.00</div> -->
            </div>
          </template>
          <!-- <template #high_form="{ form }">
            <el-form
              :model="form"
              label-align="right"
              label-width="100"
              size="default"
              label-position="top"
            >
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="">
                    <el-select
                      v-model="form.goods_source"
                      clearable
                      placeholder="产品来源"
                      class="w-full"
                    >
                      <el-option
                        v-for="item in options['goods.GoodsSpu']?.[0].goodsSourceText"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="">
                    <select-logistics
                      class="w-full"
                      v-model="form.logistics_attributess"
                      placeholder="物流属性"
                    ></select-logistics>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="">
                    <el-select
                      v-model="form.brand_type"
                      clearable
                      placeholder="品牌类型"
                      class="w-full"
                    >
                      <el-option
                        v-for="item in options['goods.GoodsSpu']?.[0].brandTypeText"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="">
                    <select-brand
                      class="w-full"
                      v-model="form.brand_id"
                      :multiple="true"
                      placeholder="产品品牌"
                    ></select-brand>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="">
                    <VGroup>
                      <el-select
                        v-model="form.purchaseRange.type"
                        placeholder="请选择"
                        style="width: 90px"
                      >
                        <el-option
                          v-for="item in purchaseList"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                      <el-input-number
                        v-model="form.purchaseRange.start"
                        :controls="false"
                        placeholder="输入"
                        style="width: 80px"
                      />
                      <div class="v-group-item"><svg-icon icon-class="qujian" /></div>
                      <el-input-number
                        v-model="form.purchaseRange.end"
                        :controls="false"
                        placeholder="输入"
                        style="width: 80px"
                      />
                      <div class="v-group-item">CNY</div>
                    </VGroup>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="">
                    <VGroup>
                      <el-select
                        v-model="form.weightRange.type"
                        placeholder="请选择"
                        style="width: 90px"
                      >
                        <el-option
                          v-for="item in weightList"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                      <el-input-number
                        v-model="form.weightRange.start"
                        :controls="false"
                        placeholder="输入"
                        style="width: 90px"
                      />
                      <div class="v-group-item"><svg-icon icon-class="qujian" /></div>
                      <el-input-number
                        v-model="form.weightRange.end"
                        :controls="false"
                        placeholder="输入"
                        style="width: 90px"
                      />
                      <div class="v-group-item">G</div>
                    </VGroup>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="">
                    <el-select
                      v-model="form.goods_tag"
                      clearable
                      placeholder="产品标签"
                      class="w-full"
                      multiple
                    >
                      <el-option
                        v-for="item in options['goods.GoodsSpu']?.[0].goodsTagText"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="">
                    <el-select
                      v-model="form.authentication"
                      clearable
                      placeholder="是否需要证书"
                      class="w-full"
                    >
                      <el-option
                        v-for="item in options['goods.GoodsSpu']?.[0].authenticationText"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item label="">
                    <el-select
                      v-model="form.plug_specification"
                      clearable
                      placeholder="插头规格"
                      class="w-full"
                    >
                      <el-option
                        v-for="item in options['goods.GoodsSkuSalesInfo']?.[0]
                          .plugSpecificationText"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="">
                    <VGroup>
                      <el-input-number
                        v-model="form.salesRange.start"
                        :controls="false"
                        placeholder="最低总销量"
                        style="width: 148px"
                      />
                      <div class="v-group-item"><svg-icon icon-class="qujian" /></div>
                      <el-input-number
                        v-model="form.salesRange.end"
                        :controls="false"
                        placeholder="最高总销量"
                        style="width: 148px"
                      />
                    </VGroup>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="">
                    <VGroup>
                      <el-input-number
                        v-model="form.inventoryRange.start"
                        :controls="false"
                        placeholder="最低库存"
                        style="width: 148px"
                      />
                      <div class="v-group-item"><svg-icon icon-class="qujian" /></div>
                      <el-input-number
                        v-model="form.inventoryRange.end"
                        :controls="false"
                        placeholder="最高库存"
                        style="width: 148px"
                      />
                    </VGroup>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </template> -->
          <template #toolbar_btns>
            <template v-if="activeName == 0">
              <VButton
                auth="/goods/goods-management/spu-list/add"
                type="primary"
                icon="Plus"
                @click="add"
                >新增产品
              </VButton>
              <VButton
                auth="/goods/goods-management/spu-list/addCombination"
                @click="addCombination"
                >新增销售组合SKU</VButton
              >
              <BatchOperation
                :batchOptions="batchOptions"
                :getTable="getBatchTableSelect"
              />
              <VButton auth="/goods/goods-management/spu-list/copy" @click="copyGoods">
                <svg-icon icon-class="copy" />复制商品
              </VButton>
              <VButton auth="/goods/goods-management/spu-list/delete" @click="deleteRow">
                <svg-icon class="base-red-color" icon-class="del" />删除</VButton
              >
            </template>
            <template v-if="activeName == 1">
              <el-button @click="recover"> 恢复SKU</el-button>
            </template>

            <div class="flex ml-auto" v-if="activeName == 0">
              <div class="mr-3 flex items-center">
                <span class="total-round mr-1"></span
                ><span class="text-[var(--base-sub-text-color)]"> SPU数量：</span
                ><span class="text-bold text-[var(--base-text-color)]">{{
                  tableCount?.spu_count.value
                }}</span>
              </div>
              <div class="mr-3 flex items-center">
                <span class="total-round mr-1"></span
                ><span class="text-[var(--base-sub-text-color)]">SKU数量：</span
                ><span class="text-bold text-[var(--base-text-color)]">{{
                  tableCount?.sku_count.value
                }}</span>
              </div>
            </div>
            <VButton
              :class="activeName == 1 ? 'ml-auto' : ''"
              auth="/goods/goods-management/spu-list/export"
              @click="handleExport"
            >
              <i class="dk-iconfont icon-Upload" />导出</VButton
            >
          </template>
        </VTable>
      </div>
    </div>
  </VPage>
  <AddCombinationSKU ref="combinationSKURef" @query="queryForm"></AddCombinationSKU>
  <ChangeState ref="changeStateRef"></ChangeState>
  <CertificateInformation
    ref="certificateRef"
    :options="options"
  ></CertificateInformation>
  <VLog
    ref="roleLog"
    class="dialogPublic"
    :api="queryLogList"
    options="spuId"
    :isSearch="true"
  ></VLog>
  <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>
  <saiheResult ref="resultRef"></saiheResult>
  <HistorySupplierPrice ref="HistorySupplierPriceRef"></HistorySupplierPrice>
  <CostDetails ref="CostDetailsRef"></CostDetails>
  <stockInfo ref="stockInfoRef"></stockInfo>
</template>
<script setup name="Goods-managementSpu-list" lang="jsx">
import {
  querySpuList,
  querySkuList,
  queryConditionList,
  conditionSave,
  spuRecover,
  conditionDelete,
  queryLogList,
  spuDelete,
} from "../api";
import { getLock } from "@/views/task/product/api.js";
import { getOptions, pushsaihe, pullsaihe } from "@/api/index.js";
import AdvancedSearch from "../components/AdvancedSearch";
import AddCombinationSKU from "../components/AddCombination/index.vue";
import ChangeState from "../components/ChangeState";
import CertificateInformation from "./components/CertificateInformation";
import VLog from "@/components/VLog";
import VImage from "@/components/Image/index.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { nextTick, ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import SelectWarehouse from "@/components/SelectWarehouse";
import RecommendedTagUI from "./components/RecommendedTagUI";
import DerivedCenter from "@/components/DerivedCenter";
import SelectSupplie from "@/components/SelectSupplie";
import saiheResult from "@/components/saiheResult";
import CategoryWrap from "@/components/CategoryWrap";
import {
  batchOptions,
  skuOptionss,
  languageOptions,
  timeOptions,
  personOptions,
  purchaseList,
  weightList,
  whetherOptions,
  salesStatusOptions,
  supplyStatusOptions,
  cleanProductStatusOptions,
  productStatusOptions,
} from "./data.js";
import BatchOperation from "@/views/task/product/components/BatchOperation/index.vue";
import HistorySupplierPrice from "@/views/task/product/components/HistorySupplierPrice.vue";
import childCombinationSKU from "@/components/Dialog/childCombinationSKU/index.vue"; // 组合SKU 显示内容
import CostDetails from "../../task/product/components/CostDetails";
import stockInfo from "@/components/Dialog/stockInfo/index.vue";

const tableRef = ref();
const router = useRouter();

const data = reactive({
  fieldOptions: null,
  rowId: null,
  options: {},
  tableCount: null,
  activeName: 0,
  searchOptions: [],
  searchId: null,
  searchName: "",
  isShowLeft: true,
  tabFilterList: [],
  containerWidth: 300,
  historySupplierData: {},
});

const {
  fieldOptions,
  options,
  tableCount,
  activeName,
  searchOptions,
  searchName,
  isShowLeft,
  tabFilterList,
  containerWidth,
  historySupplierData,
} = toRefs(data);

// 获取
const fetchOption = () => {
  getOptions({
    name: [
      "goods.GoodsSpu",
      "goods.GoodsSku",
      "goods.GoodsSkuSalesInfo",
      "goods.GoodsSkuSupplier",
      "goods.GoodsSkuAccessories",
      "goods.GoodsSkuSupplier",
      "gallery.GoodsSkuGalleryContents",
      "goods.GoodsSkuIdentificationProcessing",
    ],
  }).then((res) => {
    options.value = res.data;
  });
};
fetchOption();

provide("options", options);

const tabList = [
  {
    label: "产品池",
    name: 0,
  },
  // {
  //   label: "产品回收池",
  //   name: 1,
  //   auth: "/goods/goods-management/spu-list/recyclePool",
  // },
];

const handleChange = (val) => {
  tableRef.value.setForm({
    is_delete: val,
  });
  refresh();
};

const tableOptins = reactive({
  treeConfig: {
    transform: true,
    rowField: "name",
    parentField: "id",
    lazy: true,
    hasChild: "hasChild",
    loadMethod({ row }) {
      return fetchChildListApi(row);
    },
  },
  sortConfig: { remote: true, trigger: "cell", orders: ["desc", "asc", null] }, // 默认远程排序
  showHeaderOverflow: false,
  showOverflow: false,
  rowConfig: { height: 120, isHover: true },
  tooltipConfig: {
    showAll: false,
  },
  isToggle: true,
  scrollY: {
    enabled: true,
    gt: 10,
  },
  formConfig: {
    save: "spu-list",
    data: {
      skuRange: { type: "sku", value: [], range: false },
      spu: "",
      languageRange: { type: "sku_cn_title", value: [], range: true },
      timeRange: { type: "dev_add_time", value: [], range: true },
      personRange: { type: "developer_id", value: [], range: false },
      warehouse_id: null,
      sales_status: "",
      purchase_status: "",
      is_combination: "",
      field_3: "",
      product_attribute: "",
      sample_testing: "",
      purchaseRange: { type: "purchase_price", value: [], range: true },
      weightRange: { type: "packing_weight_g", value: [], range: true },
      goods_source: "",
      logistics_attributes: "",
      brand_type: [],
      brand_name: "",
      supplier_id: "",
      goods_tag: "",
      purchaseRange: { type: "purchase_price", value: [], range: true },
      weightRange: { type: "packing_weight_g", value: [], range: true },
      plug_specification: "",
      inventoryRange: { type: "inventory", value: [], range: true },
      salesRange: { type: "spu_sales_volume_all", value: [], range: true },
      salesStatusRange: { type: "sales_status", value: [], range: false },
      supplyStatusRange: { type: "supply_status", value: [], range: false },
      cleanProductStatusRange: { type: "clean_product_status", value: [], range: false },
      productStatusRange: { type: "product_status", value: [], range: false },
    },
  },
  scrollY: {
    enabled: true,
    gt: 10,
  },
  columns: [
    { type: "checkbox", width: "40" },
    {
      field: "name",
      title: "产品",
      width: "400",
      treeNode: "tree-node",
      slots: {
        default: ({ row, level }) => {
          return (
            <div class="relative w-full">
              <div class="relative float-left" style="width:100px;height:100px">
                {row.brand_type != 1 && (
                  <div
                    class={[
                      "absolute",
                      "text-white",
                      "absolute-radius",
                      "z-10",
                      row.brand_type == 1 ? "bg-red-600" : "bg-gray-600",
                    ]}
                  >
                    {row.brand_type_text}
                  </div>
                )}
                {level == 1 ? (
                  <VImage
                    src={row.attr_img_watermark || row.attr_img}
                    width={100}
                    height={100}
                    preview={false}
                    onClick={() => handlePreview(row)}
                  ></VImage>
                ) : (
                  <VImage
                    src={row.main_img_watermark || row.main_img}
                    width={100}
                    height={100}
                    preview={false}
                    onClick={() => handlePreview(row)}
                  ></VImage>
                )}
                {level == 0 ? (
                  <div
                    class="absolute bottom-0 left-[1px] h-6 w-[98px] base-bg-color text-white text-center cursor-pointer rounded-b"
                    on-click={() => handleAppointment()}
                  >
                    生成刊登草稿
                  </div>
                ) : (
                  ""
                )}
              </div>
              <div class="ml-[105px]">
                <div class="w-full flex justify-start">
                  <div class="truncate flex-1 w-24 text-[14px] base-text-color cursor-pointer">
                    <span>
                      {" "}
                      {level == 0 ? (
                        <VText
                          type="button"
                          title="SPU"
                          value={row.spu}
                          copy={true}
                          onClick={() => handleView(row)}
                        ></VText>
                      ) : (
                        <VText
                          title="SKU"
                          value={row.sku}
                          copy={true}
                          onClick={() => handleView(row)}
                        ></VText>
                      )}
                    </span>
                  </div>
                </div>
                <div class="w-full mr-2">
                  {level == 1 && (
                    <VText title="自定义SKU" value={row.custom_sku} copy={true}></VText>
                  )}
                </div>
                <div>
                  {level == 0 ? (
                    <span class="truncate">
                      <span class="text-[var(--base-sub-text-color)]">SPU状态：</span>
                      {row.spu_status_text}
                    </span>
                  ) : (
                    <span class="truncate">
                      <span class="text-[var(--base-sub-text-color)]">SKU状态：</span>
                      {row.product_status_text}
                    </span>
                  )}
                </div>
                {level == 0 ? (
                  <div class="flex justify-start mb-1">
                    <VText value={row.spu_category_text}></VText>
                  </div>
                ) : (
                  ""
                )}

                <div class="flex justify-start flex-wrap">
                  {level == 0 ? (
                    row.recommended_level ? (
                      <el-tooltip
                        class="item"
                        effect="dark"
                        content="SPU等级"
                        placement="top"
                      >
                        <div class="product_level_icon mr-1">
                          <svg-icon
                            icon-class={"product_level" + row.recommended_level}
                          ></svg-icon>
                        </div>
                      </el-tooltip>
                    ) : (
                      ""
                    )
                  ) : row.product_level ? (
                    <el-tooltip
                      class="item"
                      effect="dark"
                      content="产品等级"
                      placement="top"
                    >
                      <div class="product_level_icon mr-1">
                        <svg-icon
                          icon-class={"product_level" + row.product_level}
                        ></svg-icon>
                      </div>
                    </el-tooltip>
                  ) : (
                    ""
                  )}
                  {level == 1 && row.purchase_days && row.purchase_days > 0 ? (
                    <el-tooltip
                      class="item"
                      effect="dark"
                      content="采购天数"
                      placement="top"
                    >
                      <div class="btn-style mb-1">{row.purchase_days} 天</div>
                    </el-tooltip>
                  ) : (
                    ""
                  )}
                  {row.min_order && row.min_order != "0" ? (
                    <el-tooltip
                      class="item"
                      effect="dark"
                      content="起批量"
                      placement="top"
                    >
                      <div class="btn-style mb-1">{row.min_order} 件</div>
                    </el-tooltip>
                  ) : (
                    ""
                  )}
                  <el-tooltip
                    class="item"
                    effect="dark"
                    content={row.is_combination_text}
                    placement="top"
                  >
                    <div class="btn-style mb-1">{row.is_combination_text} </div>
                  </el-tooltip>
                  {row.product_attribute_text ? (
                    <el-tooltip
                      class="item"
                      effect="dark"
                      content={row.product_attribute_text}
                      placement="top"
                    >
                      <div class="btn-style mb-1">{row.product_attribute_text}</div>
                    </el-tooltip>
                  ) : (
                    ""
                  )}
                  <el-tooltip
                    class="item"
                    effect="dark"
                    content="物流属性"
                    placement="top"
                  >
                    <div class="btn-style mb-1 flex items-center">
                      {row.base_logistics_attributes?.is_dangerous ? (
                        <img
                          class="w-[15px] h-[15px] mr-1"
                          src="https://xc-goods.oss-cn-shenzhen.aliyuncs.com/20240515/data/Company/%28wei%29%2B045240188d69d8949e163fd84c2a5da50138df308.png"
                        ></img>
                      ) : (
                        ""
                      )}{" "}
                      {row.logistics_attributes_name || "--"}
                    </div>
                  </el-tooltip>
                  {level == 1 && row.goods_sku_supplier?.is_refund_tax == 2 && (
                    <el-tooltip
                      class="item"
                      effect="dark"
                      content="是否退税"
                      placement="top"
                    >
                      <div class="btn-style mb-1">
                        {row.goods_sku_supplier.is_refund_tax_text || "--"}
                      </div>
                    </el-tooltip>
                  )}
                </div>
              </div>
              <div class="absolute top-0 right-0 flex">
                {level == 0 && <childCombinationSKU data={row}></childCombinationSKU>}
              </div>
            </div>
          );
        },
      },
    },
    {
      field: "product-name",
      title: "产品名称",
      width: "350",
      slots: {
        default: ({ row, level }) => {
          let key = level === 0 ? "spu" : "sku";
          return (
            <div className="column-product-name text-[#333333]">
              {row.recommended_level ? (
                <div className="re-tag">
                  <RecommendedTagUI level={row.recommended_level} />
                </div>
              ) : (
                ""
              )}
              <vText value={row[`${key}_cn_title`]} line="2"></vText>
            </div>
          );
        },
      },
    },

    {
      field: "product-type",
      title: "产品类型/采购信息",
      width: "260",
      slots: {
        default: "purchasingInformation",
      },
    },
    {
      field: "product-info",
      title: "产品信息",
      width: "200",
      slots: {
        default: ({ row, level }) => {
          if (level == 0) {
            return (
              <div class="flex items-center">
                <svg-icon icon-class="rizhi" class="rizhi" />
                <el-link
                  type="primary"
                  underline={false}
                  class="border-right"
                  onClick={() => showCertificate(row)}
                >
                  证书信息
                </el-link>
              </div>
            );
          } else {
            return (
              <div>
                <div class="text-[#333333]">毛重：{row.gross_weight_g}g</div>
                <div class=" text-[#333333]">
                  包装尺寸：{row.packing_size_cm?.length}*{row.packing_size_cm?.width}*
                  {row.packing_size_cm?.height}cm
                </div>
                <div class="text-[12px] text-[#999999]">
                  净重：{row.net_weight_g}g | 包裹重：{row.packing_weight_g}g
                </div>
                <div class="text-[12px] text-[#999999]">
                  产品尺寸：{row.product_size_cm?.length || "0.00"}*
                  {row.product_size_cm?.width || "0.00"}*
                  {row.product_size_cm?.height || "0.00"}cm
                </div>
              </div>
            );
          }
        },
      },
    },
    {
      field: "spu_sales_volume_all",
      title: "销量",
      width: "120",
      sortable: true,
      slots: {
        default: ({ row, level }) => {
          if (level == 0) {
            return (
              <div class="">
                <div class="flex items-center">
                  7天：
                  <dataAuthority
                    auth="sales_volume"
                    value={row.sales_volume?.spu_sales_volume_seven}
                  />
                </div>
                <div class="flex items-center">
                  14天：
                  <dataAuthority
                    auth="sales_volume"
                    value={row.sales_volume?.spu_sales_volume_fourteen}
                  />
                </div>
                <div class="flex items-center">
                  30天：
                  <dataAuthority
                    auth="sales_volume"
                    value={row.sales_volume?.spu_sales_volume_thirty}
                  />
                </div>
                <div class="flex items-center">
                  90天：
                  <dataAuthority
                    auth="sales_volume"
                    value={row.sales_volume?.spu_sales_volume_ninety}
                  />
                </div>
                <div class="flex items-center">
                  总销量：
                  <dataAuthority
                    auth="sales_volume"
                    value={row.sales_volume?.spu_sales_volume_all}
                  />
                </div>
              </div>
            );
          } else {
            return (
              <div class="">
                <div class="flex items-center">
                  7天：
                  <dataAuthority
                    auth="sales_volume"
                    value={row.sales_volume?.sales_volume_seven_days}
                  />
                </div>
                <div class="flex items-center">
                  14天：
                  <dataAuthority
                    auth="sales_volume"
                    value={row.sales_volume?.sales_volume_fourteen_days}
                  />
                </div>
                <div class="flex items-center">
                  30天：
                  <dataAuthority
                    auth="sales_volume"
                    value={row.sales_volume?.sales_volume_thirty_days}
                  />
                </div>
                <div class="flex items-center">
                  90天：
                  <dataAuthority
                    auth="sales_volume"
                    value={row.sales_volume?.sales_volume_ninety_days}
                  />
                </div>
                <div class="flex items-center">
                  总销量：
                  <dataAuthority
                    auth="sales_volume"
                    value={row.sales_volume?.sales_volume_all}
                  />
                </div>
              </div>
            );
          }
        },
      },
    },
    {
      field: "inventory",
      title: "库存",
      width: "170",
      slots: {
        header: [
          {
            title: "库存",
            question: `说明：<br />库存数据来源于仓库模块，同步频率：2小时同步一次<br />实时库存：仓库定时通过平台/海外仓接口，获取平台、海外仓库存，海外仓30分钟同步一次；FBA仓四小时同步一次<br />进销存库存：由仓库系统基于单据自动计算`,
            sort: "inventory",
          },
        ],
        default: ({ row, level }) => {
          if (level == 0) {
            return (
              <div>
                <div
                  class="flex items-center base-text-color cursor-pointer"
                  onClick={() => handleViewStock(row, "spu", 2)}
                >
                  <svg-icon icon-class="tongji" />
                  <div>{row.spu_real_time_inventory}</div>
                  （实时库存）
                </div>
                <div
                  class="flex items-center base-text-color cursor-pointer"
                  onClick={() => handleViewStock(row, "spu", 1)}
                >
                  <svg-icon icon-class="tongji" />
                  <div>{row.spu_inventory}</div>
                  （进销存）
                </div>
              </div>
            );
          } else {
            return (
              <div>
                <div
                  class="flex items-center base-text-color cursor-pointer"
                  onClick={() => handleViewStock(row, "sku", 2)}
                >
                  <svg-icon icon-class="tongji" />
                  <div>{row.real_time_inventory}</div>
                  （实时库存）
                </div>
                <div
                  class="flex items-center base-text-color cursor-pointer"
                  onClick={() => handleViewStock(row, "sku", 1)}
                >
                  <svg-icon icon-class="tongji" />
                  <div>{row.inventory}</div>
                  （进销存）
                </div>
              </div>
            );
          }
        },
      },
    },
    {
      field: "gross_profit",
      title: "毛利率",
      width: "160",
      slots: {
        default: ({ row, level }) => {
          if (level == 0) {
            return <div>--</div>;
          } else {
            const sales_gross_profit = computeGrossProfitMargin(
              row.income,
              row.gross_profit
            );
            const product_gross_profit = computeGrossProfitMargin(
              row.income,
              row.product_gross_margin
            );

            return (
              <div>
                <div class="flex items-center">
                  销售毛利率：
                  <dataAuthority
                    auth="sales_gross_profit"
                    value={sales_gross_profit}
                  ></dataAuthority>
                </div>
                <div class="flex items-center">
                  产品毛利率：
                  <dataAuthority
                    auth="product_gross_profit"
                    value={product_gross_profit}
                  ></dataAuthority>
                </div>
              </div>
            );
          }
        },
      },
    },
    {
      field: "operator",
      title: "操作人员",
      width: "360",
      slots: {
        default: ({ row }) => {
          return (
            <div className="w-full column-operator-time flex justify-start  text-[var(--base-text-color)]">
              <div className="lef w-3/6">
                <vText title="添加" value={row.create_user_text}></vText>
                <vText title="开发" value={row.developer_text}></vText>
                <vText title="审核" value={row.dev_reviewer_text}></vText>
                <vText title="品质" value={row.quality_inspector_text}></vText>
              </div>
              <div className="lef w-3/6">
                <vText title="采购" value={row.purchaser_text}></vText>
                <vText title="图片" value={row.img_processor_text}></vText>
                <vText title="编辑" value={row.editor_text}></vText>
              </div>
            </div>
          );
        },
      },
    },
    {
      field: "operator-time",
      title: "操作时间",
      width: "420",
      slots: {
        default: ({ row }) => {
          return (
            <div className="w-full column-operator-time flex justify-start text-[#333333]">
              <div className="lef w-3/6">
                <div class="text-xs pt-1 leading-5">
                  <span class="text-[var(--base-sub-text-color)]">开发添加: </span>
                  {row.dev_add_time}
                </div>
                <div class="text-xs pt-1 leading-5">
                  <span class="text-[var(--base-sub-text-color)]">开发审核: </span>
                  {row.dev_review_time}
                </div>
                <div class="text-xs pt-1 leading-5">
                  <span class="text-[#666666]">检测时间: </span>
                  {row.sample_testing == 1 ? row.sample_detection_time : " - "}
                </div>
              </div>
              <div>
                <div class="text-xs pt-1 leading-5">
                  <span class="text-[var(--base-sub-text-color)]">图片任务: </span>
                  {row.image_processing_time}
                </div>
                <div class="text-xs pt-1 leading-5">
                  <span class="text-[var(--base-sub-text-color)]">图片审核: </span>
                </div>
                <div class="text-xs pt-1 leading-5">
                  <span class="text-[var(--base-sub-text-color)]">刊登上架: </span>
                </div>
              </div>
            </div>
          );
        },
      },
    },
    {
      title: "操作",
      width: "76",
      fixed: "right",
      slots: {
        default: ({ row }) => {
          return (
            <div class="table-option">
              <div>
                <VButton
                  auth="/goods/goods-management/spu-list/edit-save"
                  type="primary"
                  link
                  onClick={() => handleEdit(row.spu_id)}
                >
                  编辑
                </VButton>
              </div>
              {/* <div><VButton auth="/goods/task/product/edit" type="primary" link onClick={() => handlePush(row)}>同步赛盒</VButton></div>
            <div><VButton auth="/goods/task/product/edit" type="primary" link onClick={() => handlePull(row)}>上传赛盒</VButton></div>
            <div><VButton auth="/goods/task/product/edit" type="primary" link onClick={() => handleSyncResult(row.spu_id)}>推送结果</VButton></div> */}
              <div>
                <el-button type="primary" link onClick={() => viewLog(row.spu_id)}>
                  {" "}
                  日志
                </el-button>
              </div>
            </div>
          );
        },
      },
    },
  ],
  proxyConfig: {
    seq: true,
    // sort: true,
    props: {
      result: "data",
      total: "total",
    },
    autoLoad: false,
    ajax: {
      query: async ({ page, form, sorts }) => {
        if (form.sort && form.sort.field) {
          form.order_key = form.sort.field;
          form.order_method = form.sort.rule;
        } else {
          form.order_key = "";
          form.order_method = "";
        }

        const res = await querySpuList({ ...form, ...page });
        const { count } = res.data;
        tableCount.value = res.data.count;
        const list = res.data.list.map((i) => {
          i.hasChild = true;
          return i;
        });
        return new Promise(function (resolve) {
          resolve({
            data: list,
            total: count.spu_count.value,
          });
        });
      },
    },
  },
});
//更新表格数据
const refresh = () => {
  tableRef?.value.$table.commitProxy("query");
};

const fetchChildListApi = (parentRow) => {
  return new Promise((resolve) => {
    querySkuList({
      spu_id: parentRow.spu_id,
    }).then((res) => {
      resolve(res.data);
    });
  });
};

//选中菜单树
const handleNodeClick = (data) => {
  nextTick(() => {
    if (data.type == 1) {
      tableRef?.value.setFormField("spu_category", data.spu_category);
      tableRef?.value.setFormField("all_child_user", []);
    } else if (data.type == 2) {
      tableRef?.value.setFormField("spu_category", []);
      tableRef?.value.setFormField("all_child_user", data.all_child_user);
    }
    refresh();
  });
};

const changeStateRef = ref();
const mergeSPURef = ref();
const certificateRef = ref();

const copyGoods = () => {
  const records = getSelectRow();
  if (records.length !== 1) {
    ElMessage({
      showClose: true,
      message: "请选择一条数据！",
      type: "warning",
    });
    return false;
  }

  if (records.length > 1) return ElMessage.error("只能复制一个产品!");
  router.push({
    path: "/task/product/add",
    query: {
      spuId: records[0].spu_id,
      type: "copy",
    },
  });
};

const deleteRow = async () => {
  const records = getSelectRow().map((i) => i.spu_id);
  if (records.length == 0) {
    ElMessage({
      showClose: true,
      message: "请选择一条数据！",
      type: "error",
    });
    return false;
  }
  ElMessageBox.confirm("是否删除产品信息?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "error",
    confirmButtonClass: "btnFalses",
  }).then(async () => {
    try {
      const res = await spuDelete({
        spuIds: records,
      });
      ElMessage.success(res.message);
      queryForm();
    } catch (e) {
      throw Error(e);
    }
  });
};
//获取已选中的行
const getSelectRow = () => {
  return tableRef?.value.$table.getCheckboxRecords();
};

const getBatchTableSelect = () => {
  let records = tableRef?.value.$table.getCheckboxRecords();
  return { name: "spu_ids", records };
};
// 查询条件列表
const getConditionList = async () => {
  try {
    const res = await queryConditionList({
      apiName: "spu-list",
    });
    searchOptions.value = res.data;
  } catch (e) {
    throw Error(e);
  }
};
getConditionList();

const queryForm = (data = {}) => {
  const form = tableRef.value.getForm();
  tableRef.value.setForm({ ...form, ...data });
  nextTick(() => {
    tableRef.value.query();
  });
};

const combinationSKURef = ref();
const addCombination = () => {
  nextTick(() => {
    combinationSKURef.value.open(2);
  });
};

// 新增
const add = () => {
  router.push({
    path: "/task/product/add",
    query: {
      type: "add",
    },
  });
};

const recover = async () => {
  const records = getSelectRow();
  if (records.length == 0) {
    ElMessage.error("至少选择一项");
    return;
  }
  const spuIds = records.map((i) => i.spu_id);
  try {
    const res = await spuRecover({ spuIds });
    ElMessage.success(res.message);
    initForm();
    close();
  } catch (e) {
    throw Error(e);
  }
};
// 查看
const handleView = (row) => {
  router.push({
    path: "/task/product/detail",
    query: {
      spuId: row.spu_id,
      sku: row.sku,
    },
  });
};
// 编辑
const handleEdit = async (spuId) => {
  const { data } = await getLock({ spuId });
  if (data != 0) {
    ElMessage.warning(`[${data}]正在编辑，请稍后操作；或者联系相关同事退出编辑操作。`);
    return;
  }
  router.push({
    path: "/task/product/edit",
    query: {
      spuId,
      type: "edit",
    },
  });
};
//查看日志
const roleLog = ref();
const viewLog = (id) => {
  roleLog.value.open(id);
};

const DerivedCenterRef = ref();
const handleExport = () => {
  const records = getSelectRow().map((i) => {
    return i.spu;
  });

  const uniqueArray = [...new Set(records)];

  let condition = {};
  if (uniqueArray.length) {
    condition.spu = uniqueArray;
  } else {
    condition = tableRef.value.getQueryForm();
  }
  DerivedCenterRef.value.open({
    tag_name: "goods_spu",
    condition,
  });
};

const showCertificate = (row) => {
  certificateRef.value.open("info", row.spu_id, row.authentication_text);
};

onMounted(() => {
  tabFilterList.value = tabList.filter((i) => {
    if ((window.BTN_AUTH || []).includes(i.auth) || !i.auth) {
      return i;
    }
  });
});

// 同步赛盒
const handlePush = (row) => {
  ElMessageBox({
    title: "同步赛盒",
    message: h("p", null, [
      h(
        "p",
        { style: "height: 40px" },
        `是否确认将SPU:${row.spu}数据从赛盒系统同步至商品系统?`
      ),
      h("p", { style: "color: #999999" }, `说明：`),
      h("p", { style: "color: #999999" }, `1、系统定时三十分钟同步一次赛盒数据。`),
      h(
        "p",
        { style: "color: #999999" },
        `2、此操作通过赛盒SKU获取赛盒系统数据后，即时将获取数据同步到商品系统中。`
      ),
    ]),
    showCancelButton: true,
    confirmButtonText: "确认",
    cancelButtonText: "取消",
  }).then(async (action) => {
    try {
      pullsaihe;

      const res = await pushsaihe({
        spu_id: row.spu_id,
      });
      ElMessage.success(res.message);
    } catch (e) {
      throw error(e);
    }
  });
};

// 上传赛盒
const handlePull = (row) => {
  ElMessageBox({
    title: "上传赛盒",
    message: h("p", null, [
      h("p", { style: "height: 40px" }, `是否确认将SPU:${row.spu}数据同步到赛盒系统?`),
      h("p", { style: "color: #999999" }, `说明：`),
      h(
        "p",
        { style: "color: #999999" },
        `1、系统每10分钟自动将有调整的数据上传至赛盒。`
      ),
      h(
        "p",
        { style: "color: #999999" },
        `2、此操作通过赛盒导入功能实现，点击确认后，系统即时自动在赛盒创建导入；赛盒导入功能为异步处理，一般创建导入后60秒内执行导入；可以在日志中查询导入结果。`
      ),
    ]),
    showCancelButton: true,
    confirmButtonText: "确认",
    cancelButtonText: "取消",
  }).then(async (action) => {
    try {
      const res = await pullsaihe({
        spu_id: row.spu_id,
      });
      ElMessage.success(res.message);
    } catch (e) {
      throw error(e);
    }
  });
};
const resultRef = ref();
const handleSyncResult = (spu_id) => {
  resultRef.value.open(spu_id);
};

const handleKeyUp = (event) => {
  if (event.keyCode === 13 || event.key === "Enter") {
    queryForm();
    event.stopPropagation();
  }
};

const toggle = (val, width) => {
  isShowLeft.value = val;
  if (val) {
    containerWidth.value = width;
  }
};

//图片放大
const handlePreview = (row) => {
  router.push({
    path: "/task/product/preview",
    query: {
      id: row.id,
      sku: row.sku,
    },
  });
};

// 采购记录
const HistorySupplierPriceRef = ref();
const handlePurchaseRecord = (row) => {
  HistorySupplierPriceRef.value.open(row);
};

// 头程记录
const CostDetailsRef = ref();
const handleTcRecord = (row) => {
  CostDetailsRef.value.open(row);
};

// 计算毛利率
const computeGrossProfitMargin = (income, gross) => {
  if (!income || !gross) {
    return 0;
  }

  return ((gross / income) * 100).toFixed(2) + "%";
};

// 销量
const stockInfoRef = ref();
const handleViewStock = (row, level, type) => {
  stockInfoRef.value.open(row, level, type);
};
</script>
<style scoped lang="scss">
.mr5 {
  margin-right: 5px;
}

:deep(.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content) {
  .lable {
    color: #3487ff !important;
  }
}

.selectClass {
  &:deep(.el-select__wrapper) {
    background-color: var(--base-small-bg-color) !important;
  }
}

:deep(.row--level-1) {
  .col--checkbox .vxe-cell--checkbox {
    visibility: hidden;
  }
}

:deep(.el-tabs__nav-wrap::after) {
  height: 1px;
}

:deep(.vx-table__form-content) {
  padding-top: 0;
}

:deep(.vx-table__form-content) {
  padding-top: 0;
}

:deep(.el-tabs__header) {
  margin-bottom: 0;
}

:deep(.row--level-1) {
  background-color: var(--base-small-bg-color);
}
.total-round {
  display: inline-block;
  width: 6px;
  height: 6px;
  background: #3487ff;
  border-radius: 50%;
}
</style>
<style lang="scss">
.status {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #3a4259;
}

.enable {
  color: #3e66ee;
  width: 18px;
  height: 18px;
  margin-right: 2px;
}

.disabled {
  color: #fc6271;
  width: 18px;
  height: 18px;
  margin-right: 2px;
}

.column-product-name {
  position: relative;
  min-height: 44px;

  .re-tag {
    display: inline-block;
  }
}
</style>
